import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs'
import FormData from 'form-data'
import axios from 'axios'
import {UploadInputs} from './upload-inputs'
import https from 'https'

export async function uploadToPackageFileStorage(artifact: UploadInputs) {
    if (artifact.authorization === undefined) {
        step.error('Failed to get package file storage Authorization!')
        throw new Error('PACKAGES_AUTHORIZATION is empty')
    }
    if (artifact.baseUrl === undefined) {
        step.error('Failed to get package file storage base url!')
        throw new Error('PACKAGES_BASE_URL is empty')
    }
    step.info(
        `Upload ${artifact.artifactFullName} to PACKAGE_FILE_STORAGE, and artifact version is ${artifact.artifactVersion}`
    )

    let data = new FormData()
    data.append('file', fs.createReadStream(artifact.artifactFullName))
    data.append('fileName', artifact.artifact)
    data.append('downloadFileName', artifact.artifactName)
    data.append('version', artifact.artifactVersion)
    //「unable to verify the first certificate」忽略证书验证
    const agent = new https.Agent({
        rejectUnauthorized: false
    })
    let config = {
        httpsAgent: agent,
        method: 'post',
        url: `${artifact.baseUrl}/${artifact.projectDir}`,
        headers: {
            Authorization: artifact.authorization
        },
        data: data
    }
    let resultMd5 = ''
    await axios.request(config)
        .then(function (response: {data: any}) {
            //输出写入params
            let artifactSource = 'system-packages-file'
            let res = JSON.stringify(response.data)
            let jsonData = JSON.parse(res)
            let downloadUrl = jsonData.object.url
            let packagePath = `${downloadUrl}&artifactName=${artifact.artifact}`
            resultMd5 = jsonData.object.fileMd5
            if (resultMd5 != artifact.fileMD5) {
                step.error(
                    `Md5 not matched, source fileMd5:${artifact.fileMD5}, upload fileMd5:${resultMd5}`
                )
                throw new Error('Failed to upload artifact')
            }
            let output = `${artifact.stepIdentifier}.ARTIFACT={"ARTIFACT_URL":"${jsonData.object.url}","ARTIFACT_NAME":"${artifact.artifactName}","ARTIFACT_MD5":"${jsonData.object.fileMd5}","WEB_DOWNLOAD_URL":"${packagePath}","artifact":"${artifact.artifactName}","type":${artifact.uploadType},"downloadUrl":"${jsonData.object.url}","md5":"${jsonData.object.fileMd5}","repoId":"${artifact.repoId}","version":"${artifact.artifactVersion}"}`
            let packageInfo = `PACKAGE_INFO={"packageLabel":"${artifact.artifact}","packagePath":"${packagePath}","uploadType":"${artifact.uploadType}","repoId":"${artifact.repoId}"}`
            let artifacts = `{"source":"${artifactSource}","type":"package","packageLabel":"${artifact.artifact}","objectKey": "${artifact.fileId}","bucketName": "${artifact.bucketName}","webDownloadURL":"${packagePath}","objectKeyPrefix":"${artifact.fileParentId}","name":"${artifact.artifact}","version":"${artifact.artifactVersion}","repoId":"${artifact.repoId}","fileSize":${jsonData.object.fileSize}}`
            let artifactsList = new Array()
            artifactsList.push(JSON.parse(artifacts))
            step.addOutput(output)
            step.addOutput(packageInfo)
            step.addOutput(`ARTIFACTS=` + JSON.stringify(artifactsList))
            step.info(`Artifact download URL is: ${jsonData.object.url}`)
            step.info('Upload finished')
            fs.unlinkSync(artifact.artifactFullName)
        })
        .catch(function (error: any) {
            step.error(JSON.stringify(error.message))
            if(error.response && error.response.data){
                step.error(JSON.stringify(error.response.data))
            }
            fs.unlinkSync(artifact.artifactFullName)

            throw new Error('Failed to upload artifact')
        })
}

